<template>
  <AdminLayout title="系统配置" subtitle="管理网站运营参数">
    <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
      
      <!-- 左侧导航 -->
      <div class="lg:col-span-3">
        <nav class="bg-white shadow-sm rounded-lg overflow-hidden">
          <button
            v-for="group in settings"
            :key="group.name"
            @click="activeGroup = group.name"
            type="button"
            class="w-full px-6 py-4 text-left flex items-center border-b border-gray-100 last:border-b-0 transition-colors"
            :class="{
              'bg-gray-50 border-l-4 border-l-gray-900 font-medium': activeGroup === group.name,
              'hover:bg-gray-50': activeGroup !== group.name
            }"
          >
            <div
              class="w-2 h-2 rounded-full mr-3"
              :class="{
                'bg-gray-900': activeGroup === group.name,
                'bg-gray-300': activeGroup !== group.name
              }"
            ></div>
            <span class="text-sm">{{ group.label }}</span>
          </button>
        </nav>
      </div>

      <!-- 右侧内容 -->
      <div class="lg:col-span-9">
        <!-- 物流公司管理 -->
        <div v-if="activeGroup === 'logistics'" class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-5 border-b border-gray-200">
            <div class="flex justify-between items-center">
              <div>
                <h3 class="text-lg font-medium text-gray-900">物流公司管理</h3>
                <p class="mt-1 text-sm text-gray-500">管理系统中可用的物流公司</p>
              </div>
              <button
                @click="showCreateModal = true"
                class="inline-flex items-center px-4 py-2 bg-gray-900 text-white rounded-xl hover:bg-gray-800 transition-colors"
              >
                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                </svg>
                添加物流公司
              </button>
            </div>
          </div>

          <div class="p-6">
            <div v-if="logisticsCompanies.length === 0" class="text-center py-12">
              <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
              </svg>
              <h3 class="mt-2 text-sm font-medium text-gray-900">暂无物流公司</h3>
              <p class="mt-1 text-sm text-gray-500">开始添加第一个物流公司</p>
            </div>

            <div v-else class="space-y-4">
              <div 
                v-for="company in logisticsCompanies" 
                :key="company.id"
                class="flex items-center justify-between p-4 border border-gray-200 rounded-xl hover:bg-gray-50 transition-colors"
              >
                <div class="flex items-center space-x-4">
                  <div class="flex-shrink-0">
                    <div class="w-10 h-10 bg-gray-100 rounded-lg flex items-center justify-center">
                      <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
                      </svg>
                    </div>
                  </div>
                  <div class="flex-1 min-w-0">
                    <div class="flex items-center space-x-2">
                      <p class="text-sm font-medium text-gray-900">{{ company.name }}</p>
                      <span class="text-xs text-gray-500 font-mono">({{ company.code }})</span>
                      <span 
                        class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
                        :class="company.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"
                      >
                        {{ company.is_active ? '启用' : '禁用' }}
                      </span>
                    </div>
                    <p v-if="company.phone" class="text-sm text-gray-500">{{ company.phone }}</p>
                  </div>
                </div>
                <div class="flex items-center space-x-2">
                  <button
                    @click="editCompany(company)"
                    class="text-indigo-600 hover:text-indigo-900 text-sm"
                  >
                    编辑
                  </button>
                  <button
                    @click="deleteCompany(company)"
                    class="text-red-600 hover:text-red-900 text-sm"
                  >
                    删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 其他配置项 -->
        <form v-else @submit.prevent="submit">
          <div class="bg-white shadow-sm rounded-lg">
            <!-- 标题 -->
            <div class="px-6 py-5 border-b border-gray-200">
              <h3 class="text-lg font-medium text-gray-900">
                {{ currentGroup?.label }}
              </h3>
              <p v-if="currentGroup" class="mt-1 text-sm text-gray-500">
                配置 {{ currentGroup.label.toLowerCase() }} 相关参数
              </p>
            </div>

            <!-- 表单区域 -->
            <div class="px-6 py-6 space-y-6">
              <div
                v-for="setting in currentGroup?.settings"
                :key="setting.key"
                class="space-y-2"
              >
                <label :for="setting.key" class="block text-sm font-medium text-gray-700">
                  {{ setting.label }}
                </label>
                
                <!-- 文本输入 -->
                <input
                  v-if="setting.type === 'text'"
                  :id="setting.key"
                  v-model="formData[setting.key]"
                  type="text"
                  class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                  :placeholder="setting.description"
                />
                
                <!-- 数字输入 -->
                <input
                  v-else-if="setting.type === 'number'"
                  :id="setting.key"
                  v-model.number="formData[setting.key]"
                  type="number"
                  step="0.01"
                  class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                  :placeholder="setting.description"
                />
                
                <!-- 文本域 -->
                <textarea
                  v-else-if="setting.type === 'textarea'"
                  :id="setting.key"
                  v-model="formData[setting.key]"
                  rows="4"
                  class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                  :placeholder="setting.description"
                ></textarea>
                
                <!-- 布尔值 -->
                <div v-else-if="setting.type === 'boolean'" class="flex items-center">
                  <input
                    :id="setting.key"
                    v-model="formData[setting.key]"
                    type="checkbox"
                    class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                  />
                  <label :for="setting.key" class="ml-2 block text-sm text-gray-700">
                    启用
                  </label>
                </div>
                
                <!-- 文件上传 -->
                <div v-else-if="setting.type === 'file'" class="space-y-4">
                  <!-- 当前文件预览卡片 -->
                  <div v-if="formData[setting.key]" class="bg-gray-50 border border-gray-200 rounded-lg p-4">
                    <div class="flex items-start space-x-4">
                      <!-- 文件预览 -->
                      <div class="flex-shrink-0">
                        <div class="relative">
                          <img 
                            v-if="isImageFile(formData[setting.key])"
                            :src="formData[setting.key]" 
                            :alt="setting.label"
                            class="h-16 w-16 object-contain border border-gray-300 rounded-lg bg-white shadow-sm"
                            @error="handleImageError"
                          />
                          <div 
                            v-else
                            class="h-16 w-16 bg-white border border-gray-300 rounded-lg flex items-center justify-center shadow-sm"
                          >
                            <svg class="h-8 w-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
                            </svg>
                          </div>
                          <!-- 文件类型标签 -->
                          <div class="absolute -top-1 -right-1 bg-gray-900 text-white text-xs px-2 py-1 rounded-full">
                            {{ getFileExtension(formData[setting.key]) }}
                          </div>
                        </div>
                      </div>
                      
                      <!-- 文件信息 -->
                      <div class="flex-1 min-w-0">
                        <div class="flex items-center space-x-2 mb-1">
                          <h4 class="text-sm font-medium text-gray-900 truncate">{{ getFileName(formData[setting.key]) }}</h4>
                          <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                            <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                              <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                            </svg>
                            当前文件
                          </span>
                        </div>
                        <p class="text-xs text-gray-500 mb-2">{{ setting.description }}</p>
                        <div class="flex items-center space-x-2">
                          <button
                            type="button"
                            @click="removeFile(setting.key)"
                            class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-red-700 bg-red-50 border border-red-200 rounded-md hover:bg-red-100 transition-colors"
                          >
                            <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                            移除
                          </button>
                          <button
                            type="button"
                            @click="resetFileInput(setting.key)"
                            class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-gray-700 bg-gray-50 border border-gray-200 rounded-md hover:bg-gray-100 transition-colors"
                          >
                            <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                            </svg>
                            重置
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 文件上传区域 -->
                  <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors">
                    <div class="space-y-4">
                      <!-- 上传图标 -->
                      <div class="mx-auto w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center">
                        <svg class="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                        </svg>
                      </div>
                      
                      <!-- 上传说明 -->
                      <div>
                        <p class="text-sm font-medium text-gray-900">选择文件或拖拽到此处</p>
                        <p class="text-xs text-gray-500 mt-1">{{ setting.description }}</p>
                      </div>
                      
                      <!-- 文件输入 -->
                      <div class="flex justify-center">
                        <label 
                          :for="setting.key"
                          class="cursor-pointer inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
                        >
                          <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                          </svg>
                          选择文件
                        </label>
                        <input
                          :id="setting.key"
                          type="file"
                          @change="handleFileUpload($event, setting.key)"
                          :accept="getFileAccept(setting.key)"
                          class="hidden"
                        />
                      </div>
                      
                      <!-- 支持格式提示 -->
                      <div class="flex justify-center">
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                          <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
                          </svg>
                          支持 {{ getFileAccept(setting.key) }} 格式
                        </span>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 可见性指示器 -->
                  <div class="flex items-center justify-center">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                      <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                        <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd" />
                      </svg>
                      此配置对前台可见
                    </span>
                  </div>
                </div>

                <!-- 说明文字 (非文件类型) -->
                <p v-if="setting.description && setting.type !== 'file'" class="text-sm text-gray-500">
                  {{ setting.description }}
                </p>

                <!-- 公开标识 (非文件类型) -->
                <p v-if="setting.is_public && setting.type !== 'file'" class="text-xs text-blue-600">
                  ✓ 此配置对前台可见
                </p>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex justify-end space-x-3">
              <button
                type="button"
                @click="resetSystemForm"
                class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
              >
                重置
              </button>
              <button
                type="submit"
                :disabled="processing"
                class="px-4 py-2 border border-transparent rounded-md text-sm font-medium text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {{ processing ? '保存中...' : '保存设置' }}
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- 物流公司弹窗 -->
    <div v-if="showCreateModal || showEditModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50" @click="closeModal">
      <div class="relative top-20 mx-auto p-6 border w-96 shadow-lg rounded-2xl bg-white" @click.stop>
        <div class="mt-3">
          <h3 class="text-lg font-medium text-gray-900 mb-4">
            {{ showCreateModal ? '添加物流公司' : '编辑物流公司' }}
          </h3>
          
          <form @submit.prevent="submitForm" class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">公司名称 *</label>
              <input
                v-model="form.name"
                type="text"
                required
                class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                placeholder="请输入物流公司名称"
              >
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">公司代码 *</label>
              <input
                v-model="form.code"
                type="text"
                required
                class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900 font-mono"
                placeholder="如：SF、YTO、ZTO"
              >
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">官网地址</label>
              <input
                v-model="form.website"
                type="url"
                class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                placeholder="https://www.example.com"
              >
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">客服电话</label>
              <input
                v-model="form.phone"
                type="tel"
                class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                placeholder="400-123-4567"
              >
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">公司描述</label>
              <textarea
                v-model="form.description"
                rows="3"
                class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                placeholder="请输入公司描述"
              ></textarea>
            </div>

            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <input
                  v-model="form.is_active"
                  type="checkbox"
                  class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                />
                <label class="ml-2 block text-sm text-gray-700">启用状态</label>
              </div>
              <div class="flex items-center space-x-2">
                <label class="text-sm text-gray-700">排序：</label>
                <input
                  v-model="form.sort_order"
                  type="number"
                  min="0"
                  class="w-20 px-3 py-2 border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                />
              </div>
            </div>

            <div class="flex justify-end space-x-3 pt-4">
              <button
                type="button"
                @click="closeModal"
                class="px-6 py-3 border border-gray-300 text-gray-700 rounded-2xl hover:bg-gray-50 transition-colors"
              >
                取消
              </button>
              <button
                type="submit"
                :disabled="isSubmitting"
                class="px-6 py-3 bg-gray-900 text-white rounded-2xl hover:bg-gray-800 transition-colors disabled:opacity-50"
              >
                {{ isSubmitting ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </AdminLayout>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { router, Link } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { useNotification } from '@/composables/useNotification'

const props = defineProps({
  settings: {
    type: Array,
    required: true
  },
  activeGroup: {
    type: String,
    default: 'basic'
  },
  logisticsCompanies: {
    type: Array,
    default: () => []
  }
})

const { showSuccess, showError } = useNotification()

// 当前活动分组
const activeGroup = ref(props.activeGroup)

// 弹窗状态
const showCreateModal = ref(false)
const showEditModal = ref(false)
const isSubmitting = ref(false)
const editingCompany = ref(null)

// 表单数据
const form = ref({
  name: '',
  code: '',
  website: '',
  phone: '',
  description: '',
  is_active: true,
  sort_order: 0
})

// 当前分组数据
const currentGroup = computed(() => {
  return props.settings.find(g => g.name === activeGroup.value)
})

// 表单数据
const formData = ref({})

// 初始化表单数据
const initializeFormData = () => {
  const data = {}
  props.settings.forEach(group => {
    group.settings.forEach(setting => {
      // 根据类型初始化值
      if (setting.type === 'boolean') {
        data[setting.key] = setting.value === '1' || setting.value === true
      } else if (setting.type === 'number') {
        data[setting.key] = parseFloat(setting.value) || 0
      } else {
        data[setting.key] = setting.value || ''
      }
    })
  })
  formData.value = data
}

// 文件处理函数
const isImageFile = (filePath) => {
  if (!filePath) return false
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.svg', '.webp']
  return imageExtensions.some(ext => filePath.toLowerCase().endsWith(ext))
}

const getFileName = (filePath) => {
  if (!filePath) return ''
  return filePath.split('/').pop() || filePath
}

const getFileExtension = (filePath) => {
  if (!filePath) return ''
  const fileName = getFileName(filePath)
  const lastDot = fileName.lastIndexOf('.')
  return lastDot > 0 ? fileName.substring(lastDot + 1).toUpperCase() : 'FILE'
}

const getFileAccept = (key) => {
  if (key === 'site_logo') {
    return '.svg,.png,.jpg,.jpeg,.webp'
  } else if (key === 'site_favicon') {
    return '.svg,.ico,.png'
  }
  return '*'
}

const handleFileUpload = (event, key) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 创建临时 URL 用于预览
  const tempUrl = URL.createObjectURL(file)
  formData.value[key] = tempUrl
  
  // 这里可以添加上传到服务器的逻辑
  // 目前只是本地预览，实际项目中需要上传到服务器
  console.log(`文件上传: ${key}`, file.name)
}

const removeFile = (key) => {
  // 释放临时 URL
  if (formData.value[key] && formData.value[key].startsWith('blob:')) {
    URL.revokeObjectURL(formData.value[key])
  }
  formData.value[key] = ''
}

const resetFileInput = (key) => {
  const input = document.getElementById(key)
  if (input) {
    input.value = ''
  }
  removeFile(key)
}

const handleImageError = (event) => {
  event.target.style.display = 'none'
}

initializeFormData()

// 重置表单（系统设置）
const resetSystemForm = () => {
  initializeFormData()
}

// 处理状态
const processing = ref(false)

// 提交表单
const submit = () => {
  if (!currentGroup.value) return
  
  processing.value = true
  
  // 只提交当前分组的设置
  const settingsToUpdate = currentGroup.value.settings.map(setting => ({
    key: setting.key,
    value: formData.value[setting.key]
  }))
  
  router.post(route('admin.system-settings.update'), {
    settings: settingsToUpdate
  }, {
    preserveScroll: true,
    onSuccess: () => {
      processing.value = false
      // 成功消息由后端flash提供
    },
    onError: (errors) => {
      processing.value = false
      const firstError = Object.values(errors)[0]
      if (firstError) {
        showError('保存失败', Array.isArray(firstError) ? firstError[0] : firstError)
      }
    },
    onFinish: () => {
      processing.value = false
    }
  })
}

// 编辑物流公司
const editCompany = (company) => {
  editingCompany.value = company
  form.value = {
    name: company.name,
    code: company.code,
    website: company.website || '',
    phone: company.phone || '',
    description: company.description || '',
    is_active: company.is_active,
    sort_order: company.sort_order
  }
  showEditModal.value = true
}

// 关闭弹窗
const closeModal = () => {
  showCreateModal.value = false
  showEditModal.value = false
  editingCompany.value = null
  resetForm()
}

// 重置表单
const resetForm = () => {
  form.value = {
    name: '',
    code: '',
    website: '',
    phone: '',
    description: '',
    is_active: true,
    sort_order: 0
  }
}

// 提交表单
const submitForm = () => {
  isSubmitting.value = true
  
  const url = showCreateModal.value 
    ? route('logistics-companies.store')
    : route('logistics-companies.update', editingCompany.value.id)
  
  const method = showCreateModal.value ? 'post' : 'put'
  
  router[method](url, form.value, {
    onSuccess: () => {
      isSubmitting.value = false
      closeModal()
      showSuccess('操作成功', showCreateModal.value ? '物流公司创建成功' : '物流公司更新成功')
    },
    onError: (errors) => {
      isSubmitting.value = false
      const firstError = Object.values(errors)[0]
      if (firstError) {
        showError('操作失败', Array.isArray(firstError) ? firstError[0] : firstError)
      }
    }
  })
}

// 删除物流公司
const deleteCompany = (company) => {
  if (confirm(`确定要删除物流公司 "${company.name}" 吗？`)) {
    router.delete(route('logistics-companies.destroy', company.id), {
      onSuccess: () => {
        showSuccess('删除成功', '物流公司已删除')
      },
      onError: () => {
        showError('删除失败', '请重试')
      }
    })
  }
}

// 监听分组切换，更新URL
watch(activeGroup, (newGroup) => {
  router.get(
    route('admin.system-settings', { group: newGroup }),
    {},
    { 
      preserveState: true,
      preserveScroll: true,
      only: []
    }
  )
})
</script>

